package com.hw.one.dam2.controller;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSONObject;
import com.hw.one.core.controller.BaseController;
import com.hw.one.core.result.MsgResult;
import com.hw.one.dam2.common.DamConstant;
import com.hw.one.dam2.service.IStatisticalOverviewService;
import com.hw.one.dam2.util.CalendarUtil;
import com.hw.one.ext.util.UserUtil;
import org.springframework.web.bind.annotation.RestController;

/**
 * Copyright 2017 汉威.智慧环保事业部.
 * Created by 李亚坤 on 2017/03/24 09:55.
 *
 * 统计概览查询接口
 *
 */
@RestController
@RequestMapping(value = "statisticalOverview")
public class StatisticalOverviewController extends BaseController{

    @Autowired
    private IStatisticalOverviewService statisticalOverviewService;
    /**
     * 根据时间点,查询优良天数,首要污染物,污染物分担率
     * @author 李亚坤
     * @createtime 2017年3月24日10:03:20
     * @param request
     * @return
     */
    @RequestMapping(value = "findStatisticalOverview", method = RequestMethod.GET)
    public MsgResult findStatisticalOverview(HttpServletRequest request) {
        try {
            String endTime = request.getParameter("endTime");
            Map<String, Object> map = new HashMap<>();
            map.put("endTime", getDateStrByStr(endTime));
            // 根据登录用户，查询用户所属行政区域
            Map<String, Object> region = UserUtil.getRegion();
            String userRegionCode = (String) region.get("regionCode");
            map.put("regionCode", userRegionCode);
            //查询数据
            Object resultObj = statisticalOverviewService.findStatisticalOverview(map);

            return MsgResult.okResult(resultObj);
        }catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("查询优良天气,首要污染物,污染物分担率异常,后台异常");
        }
    }

    /**
     * 查询各污染物同环比状态
     * @author 李亚坤
     * @createtime 2017年3月24日11:15:04
     * @param request
     * @return
     */
    @RequestMapping(value = "findPollutionContrastRatio", method = RequestMethod.GET)
    public MsgResult findPollutionContrastRatio(HttpServletRequest request) {
        try {
            String ratioType = request.getParameter("type");
            String endTime = request.getParameter("endTime");
            Map<String, Object> map = new HashMap<>();
            String endTimeStr = getDateStrByStr(endTime);
            map.put("endTime", endTimeStr);
            // 根据登录用户，查询用户所属行政区域
            Map<String, Object> region = UserUtil.getRegion();
            String userRegionCode = (String) region.get("regionCode");
            map.put("regionCode", userRegionCode);
            Object resultObj = null;
            JSONObject result = new JSONObject();
            //环比
            if ("HB".equals(ratioType)) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(CalendarUtil.getDateByString(endTimeStr, DamConstant.SDF_YMD));
                String nowTime = CalendarUtil.getDateFormat(calendar.getTime(), DamConstant.SDF_YMD);
                calendar.add(Calendar.DATE, -1); //前一天
                //
                String lastTime = CalendarUtil.getDateFormat(calendar.getTime(), DamConstant.SDF_YMD);
                result.put("nowTime", nowTime);
                result.put("lastTime", lastTime);
                String lastYear = CalendarUtil.getDateFormat(calendar.getTime(), DamConstant.SDF_YMD);
                map.put("lastYear", lastYear);
                resultObj = statisticalOverviewService.findPollutionContrastRatio(map);

            }
            //同比
            if ("TB".equals(ratioType)){
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(CalendarUtil.getDateByString(endTimeStr, DamConstant.SDF_YMD));
                int nowYearNum = calendar.get(Calendar.YEAR);
                calendar.add(Calendar.YEAR, -1); //上一年
                int lastYearNum = calendar.get(Calendar.YEAR);
                //
                result.put("nowTime", nowYearNum + "年");
                result.put("lastTime", lastYearNum + "年");
                String lastYear = CalendarUtil.getDateFormat(calendar.getTime(), DamConstant.SDF_YMD);
                map.put("lastYear", lastYear);
                resultObj = statisticalOverviewService.findPollutionContrastRatio(map);
            }
            result.put("resultObj", resultObj);

            return MsgResult.okResult(resultObj);
        }catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("查询各污染物同环比状态异常,后台异常");
        }
    }


    /**
     * 查询天气空气质量趋势
     * @author 李亚坤
     * @param request
     * @return
     */
    @RequestMapping(value = "findAirQualityTrend", method = RequestMethod.GET)
    public MsgResult findAirQualityTrend(HttpServletRequest request) {
        try {
            String endTime = request.getParameter("endTime");
            Map<String, Object> map = new HashMap<>();
            String endTimeStr = getDateStrByStr(endTime);

            String startTime = endTimeStr.split("-")[0] + "-" + endTimeStr.split("-")[1] + "-01";
            map.put("endTime", endTimeStr);
            map.put("startTime", startTime);
            // 根据登录用户，查询用户所属行政区域
            Map<String, Object> region = UserUtil.getRegion();
            String userRegionCode = (String) region.get("regionCode");
            map.put("regionCode", userRegionCode);
            if ("20".equals(region.get("regionType").toString())) {
                map.put("cityRegionCode", userRegionCode);
            }
            if ("22".equals(region.get("regionType").toString())) {
                map.put("cityRegionCode", region.get("parentCode"));
            }

            Object resultObj = statisticalOverviewService.findAirQualityTrend(map);
            return MsgResult.okResult(resultObj);
        }catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("查询天气空气质量趋势异常,后台异常");
        }
    }

    /**
     * 查询辖区空气质量分析
     * @author 李亚坤
     * @createtime 2017年3月24日14:42:11
     * @param request
     * @return
     */
    @RequestMapping(value = "findAreaAirQualityAnalysis", method = RequestMethod.GET)
    public MsgResult findAreaAirQualityAnalysis(HttpServletRequest request) {
        try {

            String endTime = request.getParameter("endTime");
            Map<String, Object> map = new HashMap<>();
            String endTimeStr = getDateStrByStr(endTime);
            map.put("endTime", endTimeStr);

            Calendar calendar = Calendar.getInstance();
            calendar.setTime(CalendarUtil.getDateByString(endTimeStr, DamConstant.SDF_YMD));
            calendar.add(Calendar.DATE, -1); //前一天
            //
            String yesterday = CalendarUtil.getDateFormat(calendar.getTime(), DamConstant.SDF_YMD);
            map.put("yesterday", yesterday);

            calendar.setTime(CalendarUtil.getDateByString(endTimeStr, DamConstant.SDF_YMD));
            calendar.add(Calendar.YEAR, -1); //前一年
            //
            String lastYear = CalendarUtil.getDateFormat(calendar.getTime(), DamConstant.SDF_YMD);
            map.put("lastYear", lastYear);
            map.put("factor", StringUtils.isEmpty(request.getParameter("factor")) ? "AQI" : request.getParameter("factor"));
            Object resultObj = null;
            // 根据登录用户，查询用户所属行政区域
            Map<String, Object> region = UserUtil.getRegion();
            String userRegionCode = (String) region.get("regionCode");
            map.put("regionCode", userRegionCode);
            if ("20".equals(region.get("regionType").toString())) {
                resultObj = statisticalOverviewService.findAreaAirQualityAnalysisByFactor(map);
            }

            JSONObject data = new JSONObject();
            data.put("resultObj", resultObj);
            return MsgResult.okResult(data);
        }catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("查询辖区空气质量分析异常,后台异常");
        }
    }

    /**
     * 查询站点数据上传率
     * @author 李亚坤
     * @createtime 2017年7月17日14:01:03
     * @param request
     * @return
     */
    @RequestMapping(value = "findSiteAirUploadRate", method = RequestMethod.GET)
    public MsgResult findSiteAirUploadRate(HttpServletRequest request) {
        try {
            return MsgResult.okResult(statisticalOverviewService.findSiteAirUploadRate(request));
        }catch (Exception e) {
            e.printStackTrace();
            return MsgResult.errorResult("查询站点上传率异常,后台异常");
        }
    }

    public String getDateStrByStr(String dateStr) throws Exception{
        Calendar calendar = Calendar.getInstance();
        Date now = new Date();
        calendar.setTime(now);
        calendar.add(Calendar.DATE, -1);
        //如果日期大于昨天的日期或者为空的话,就取昨天的日期
        String yesterday = CalendarUtil.getDateFormat(calendar.getTime(), DamConstant.SDF_YMD);

        String time = StringUtils.isEmpty(dateStr) ||
                CalendarUtil.getDateByString(dateStr, DamConstant.SDF_YMD).getTime() >
                        CalendarUtil.getDateByString(yesterday, DamConstant.SDF_YMD).getTime() ?
                yesterday: dateStr;

        return time;
    }
}
